//
//  MenuLayout.m
//  TopMenu
//
//  Created by liwei on 2017/6/14.
//  Copyright © 2017年 liwei. All rights reserved.
//

#import "MenuLayout.h"

@interface MenuLayout ()
/*
 * contain item attributes
 */
@property (nonatomic,strong) NSArray *attrs;

@end

@implementation MenuLayout

- (void)prepareLayout {

    [super prepareLayout];
    
    self.minimumLineSpacing = 0;
    self.minimumInteritemSpacing = 0;
    self.sectionInset = UIEdgeInsetsMake(0, self.itemSize.width, 0, self.itemSize.width);
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
}

/**
 * 当collectionView的显示范围发生改变的时候，是否需要重新刷新布局
 * 一旦重新刷新布局，就会重新调用下面的方法：
 * 1.prepareLayout
 * 2.layoutAttributesForElementsInRect:方法
 */
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {

    return YES;
}

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {

    //计算出最终显示的矩形框，遍历改矩形框内的cell相对于中心的位置，进而调整cell
    CGRect currentRect;
    currentRect.origin.x = proposedContentOffset.x;
    currentRect.origin.y = 0;
    currentRect.size = CGSizeMake(self.collectionView.frame.size.width, self.collectionView.frame.size.height);
    //拿到矩形框内布局好的cell属性
    NSArray *attrs = [super layoutAttributesForElementsInRect:currentRect];
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width * 0.5;
    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attr in attrs) {
        if (ABS(minDelta) > ABS(attr.center.x - centerX)) {
            minDelta = attr.center.x - centerX;
        }
    }
    //修改偏移量
    proposedContentOffset.x += minDelta;
    
    return proposedContentOffset;
}

/**
 * UICollectionViewLayoutAttributes *attrs;
 * 1.一个cell对应一个UICollectionViewLayoutAttributes对象
 * 2.UICollectionViewLayoutAttributes对象决定了cell的frame
 * 这个方法的返回值是一个数组（数组里面存放着rect范围内所有元素的布局属性）
 * 这个方法的返回值决定了rect范围内所有元素的排布（frame）
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {

    NSArray *attrs = [super layoutAttributesForElementsInRect:rect];
//    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
//    for (UICollectionViewLayoutAttributes *attr in attrs) {
//        CGFloat delay = ABS(attr.center.x - centerX);
//        CGFloat scale = 1 - (delay / self.collectionView.frame.size.width);
//        attr.transform3D = CATransform3DMakeScale(scale, scale, 1);
//    }
    self.attrs = attrs;
    return attrs;
}

/**
 * 重新刷新布局时会调用
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    return attr;
}


@end
